package edu.uclm.esi.tysw.podtube.domain;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;

import edu.uclm.esi.tysw.podtube.persistence.AudioDAO;

public class Audio {
	private String hash;
	private byte[] contenido;
	private String tempFileName;
	
	public Audio(String tempFileName, String trueFileName) throws FileNotFoundException, IOException {
		FileInputStream fi=new FileInputStream(tempFileName);
		this.contenido=new byte[fi.available()];
		fi.read(this.contenido);
		fi.close();
		this.tempFileName=tempFileName;
		this.hash=this.calculateHash().substring(40);
	}
	
	public void insert() throws SQLException, FileNotFoundException {
		AudioDAO.insert(this);
	}

	private String calculateHash() {
		String hash = "";
		for (byte aux : this.contenido) {
			int b = aux & 0xff;
			if (Integer.toHexString(b).length() == 1)
				hash += "0";
			hash += Integer.toHexString(b);
		}
		return hash;
	}

	public byte[] getContenido() {
		return contenido;
	}

	public String getHash() {
		return hash;
	}

	public String getTempFileName() {
		return tempFileName;
	}
}
